<template>
  <div class="map-container">
    <!-- 左侧 EPSG:3857 地图 -->
    <div class="map-wrapper">
      <h3>EPSG:3857 (Web墨卡托投影坐标系)</h3>
      <div id="map3857" class="map"></div>
      <div class="map-info">
        <p>特点：</p>
        <ul>
          <li>使用米为单位</li>
          <li>适合Web展示</li>
          <li>会产生形状和面积变形</li>
          <li>坐标范围很大(约±20,000,000米)</li>
        </ul>
      </div>
    </div>

    <!-- 右侧 EPSG:4326 地图 -->
    <div class="map-wrapper">
      <h3>EPSG:4326 (WGS84地理坐标系)</h3>
      <div id="map4326" class="map"></div>
      <div class="map-info">
        <p>特点：</p>
        <ul>
          <li>使用经纬度</li>
          <li>GPS设备使用此坐标系</li>
          <li>经度范围：±180°</li>
          <li>纬度范围：±90°</li>
        </ul>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <button @click="addPoints">添加示例点</button>
      <button @click="addRandomPoint">添加随机点</button>
      <button @click="clearPoints">清除点位</button>
      <div class="coordinate-info">
        <p>鼠标位置:</p>
        <p>EPSG:4326 - {{ coord4326 }}</p>
        <p>EPSG:3857 - {{ coord3857 }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { XYZ, Vector as VectorSource, WMTS } from 'ol/source';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import { Point } from 'ol/geom';
import Feature from 'ol/Feature';
import { Style, Icon, Text, Fill, Stroke } from 'ol/style';
import { fromLonLat, transform } from 'ol/proj';

export default {
  name: 'CoordinateSystemAnalysis',
  
  data() {
    return {
      map3857: null,
      map4326: null,
      source3857: null,
      source4326: null,
      coord4326: '经度: 0.000000, 纬度: 0.000000',
      coord3857: 'X: 0m, Y: 0m',
      pointIcon: '/images/markers/PP_CJ.png'
    };
  },

  mounted() {
    this.initMaps();
    this.setupMouseTracking();
  },

  methods: {
    initMaps() {
      // 初始化矢量图层
      this.source3857 = new VectorSource();
      this.source4326 = new VectorSource();
      
      const vectorLayer3857 = new VectorLayer({ source: this.source3857 });
      const vectorLayer4326 = new VectorLayer({ source: this.source4326 });

      // 创建4326的WMTS网格
      const resolutions4326 = [];
      const matrixIds4326 = [];
      const maxZoom = 18;
      const initialResolution = 1.40625; // 360度/256像素
      for (let i = 1; i <= maxZoom; i++) {
        resolutions4326.push(initialResolution / Math.pow(2, i));
        matrixIds4326.push(i.toString());
      }

      const wmtsTileGrid4326 = new WMTSTileGrid({
        origin: [-180, 90],
        resolutions: resolutions4326,
        matrixIds: matrixIds4326,
        tileSize: [256, 256]
      });

      // 创建3857地图
      this.map3857 = new Map({
        target: 'map3857',
        layers: [
          new TileLayer({
            source: new XYZ({
              url: 'http://t{0-7}.tianditu.gov.cn/vec_w/wmts?' +
                'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
                '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8c88eba266a165eac9c085724708f2f9'
            })
          }),
          // 添加天地图文字标注图层(3857)
          new TileLayer({
            source: new XYZ({
              url: 'http://t{0-7}.tianditu.gov.cn/cva_w/wmts?' +
                'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
                '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8c88eba266a165eac9c085724708f2f9'
            })
          }),
          vectorLayer3857
        ],
        view: new View({
          center: fromLonLat([87.617733, 43.792818]),
          zoom: 4,
          projection: 'EPSG:3857'
        })
      });

      // 创建4326地图
      this.map4326 = new Map({
        target: 'map4326',
        layers: [
          new TileLayer({
            source: new WMTS({
              url: 'https://t{0-7}.tianditu.gov.cn/vec_c/wmts?tk=8c88eba266a165eac9c085724708f2f9',
              layer: 'vec',
              format: 'tiles',
              matrixSet: 'c',
              style: 'default',
              projection: 'EPSG:4326',
              tileGrid: wmtsTileGrid4326,
              wrapX: true
            })
          }),
          // 添加天地图文字标注图层(4326)
          new TileLayer({
            source: new WMTS({
              url: 'https://t{0-7}.tianditu.gov.cn/cva_c/wmts?tk=8c88eba266a165eac9c085724708f2f9',
              layer: 'cva',
              format: 'tiles',
              matrixSet: 'c',
              style: 'default',
              projection: 'EPSG:4326',
              tileGrid: wmtsTileGrid4326,
              wrapX: true
            })
          }),
          vectorLayer4326
        ],
        view: new View({
          center: [87.617733, 43.792818],
          zoom: 5,
          projection: 'EPSG:4326'
        })
      });
    },

    setupMouseTracking() {
      // 跟踪两个地图的鼠标位置
      this.map3857.on('pointermove', (evt) => {
        const coord3857 = evt.coordinate;
        const coord4326 = transform(coord3857, 'EPSG:3857', 'EPSG:4326');
        
        this.coord3857 = `X: ${Math.round(coord3857[0])}m, Y: ${Math.round(coord3857[1])}m`;
        this.coord4326 = `经度: ${coord4326[0].toFixed(6)}, 纬度: ${coord4326[1].toFixed(6)}`;
      });
      
      // 4326地图鼠标位置
      this.map4326.on('pointermove', (evt) => {
        const coord4326 = evt.coordinate;
        const coord3857 = transform(coord4326, 'EPSG:4326', 'EPSG:3857');
        
        this.coord4326 = `经度: ${coord4326[0].toFixed(6)}, 纬度: ${coord4326[1].toFixed(6)}`;
        this.coord3857 = `X: ${Math.round(coord3857[0])}m, Y: ${Math.round(coord3857[1])}m`;
      });
    },

    createPointStyle(name) {
      return new Style({
        image: new Icon({
          src: this.pointIcon,
          scale: 0.5,
          anchor: [0.5, 1],
          anchorXUnits: 'fraction',
          anchorYUnits: 'fraction'
        }),
        text: new Text({
          text: name,
          offsetY: -25,
          fill: new Fill({ color: '#fff' }),
          stroke: new Stroke({
            color: 'rgba(0, 0, 0, 0.6)',
            width: 3
          }),
          backgroundFill: new Fill({
            color: 'rgba(0, 0, 0, 0.6)'
          })
        })
      });
    },

    addPoints() {
      const cities = [
        { name: '乌鲁木齐', coord: [87.617733, 43.792818] },
        { name: '克拉玛依', coord: [84.889207, 45.579889] },
        { name: '吐鲁番', coord: [89.184078, 42.947613] }
      ];

      cities.forEach(city => {
        // 在3857地图上添加点 (需要转换坐标)
        console.log(`${city.name} 3857坐标:`, fromLonLat(city.coord));
        const feature3857 = new Feature({
          geometry: new Point(fromLonLat(city.coord)),
          name: city.name
        });
        feature3857.setStyle(this.createPointStyle(city.name));
        this.source3857.addFeature(feature3857);

        // 在4326地图上添加点 (直接使用经纬度)
        console.log(`${city.name} 4326坐标:`, city.coord);
        const feature4326 = new Feature({
          geometry: new Point(city.coord),
          name: city.name
        });
        feature4326.setStyle(this.createPointStyle(city.name));
        this.source4326.addFeature(feature4326);
      });
    },

    addRandomPoint() {
      // 在新疆范围内随机生成点
      const lon = 73.5 + Math.random() * (96.4 - 73.5);
      const lat = 34.4 + Math.random() * (49.2 - 34.4);
      const name = `点位${this.source3857.getFeatures().length + 1}`;

      // 在3857地图上添加点 (需要转换坐标)
      console.log('3857坐标:', fromLonLat([lon, lat]));
      const feature3857 = new Feature({
        geometry: new Point(fromLonLat([lon, lat])),
        name: name
      });
      feature3857.setStyle(this.createPointStyle(name));
      this.source3857.addFeature(feature3857);

      // 在4326地图上添加点 (直接使用经纬度)
      console.log('4326坐标:', [lon, lat]);
      const feature4326 = new Feature({
        geometry: new Point([lon, lat]),
        name: name
      });
      feature4326.setStyle(this.createPointStyle(name));
      this.source4326.addFeature(feature4326);
    },

    clearPoints() {
      this.source3857.clear();
      this.source4326.clear();
    }
  }
};
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
  display: flex;
  background: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
}

.map-wrapper {
  flex: 1;
  margin: 0 10px;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h3 {
  text-align: center;
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.map {
  width: 100%;
  height: calc(100% - 140px);
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.map-info {
  margin-top: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 13px;
}

.map-info p {
  margin: 0 0 5px 0;
  color: #606266;
  font-weight: bold;
}

.map-info ul {
  margin: 0;
  padding-left: 20px;
  color: #606266;
}

.map-info li {
  margin: 3px 0;
}

.toolbar {
  position: absolute;
  top: 30px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.toolbar button {
  margin: 0 5px;
  padding: 8px 15px;
  border: 1px solid #dcdfe6;
  background: white;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  color: #606266;
}

.toolbar button:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.coordinate-info {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
  font-size: 13px;
  color: #606266;
}

.coordinate-info p {
  margin: 5px 0;
}
</style>